package com.github.cyf.cacheManager;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenyifan
 * @create 2025-02-06 9:35
 */
@Slf4j
public abstract class AbstractCacheManager implements CacheManager {

    private static final ConcurrentHashMap<String, ReentrantLock> LOCK_MAP = new ConcurrentHashMap<>();

    @Override
    public void initCache() {
        // 加个锁，防止出现并发更新问题
        ReentrantLock lock = LOCK_MAP.computeIfAbsent(getCacheName().getName(), k -> new ReentrantLock());
        lock.lock();
        try {
            loadCache();
            afterInitCache();
            log.info("init cache {}", getCacheName());
        } catch (Exception e) {
            log.error("init cache {} error", getCacheName(), e);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void refreshCache() {
        // 加个锁，防止出现并发更新问题
        ReentrantLock lock = LOCK_MAP.computeIfAbsent(getCacheName().getName(), k -> new ReentrantLock());
        lock.lock();
        try {
            loadCache();
            afterRefreshCache();
            log.info("refresh cache {}", getCacheName());
        } catch (Exception e) {
            log.error("refresh cache {} error", getCacheName(), e);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public int getOrder() {
        return getCacheName().getOrder();
    }

    /**
     * 查询数据仓库，并加载到缓存数据
     */
    protected abstract void loadCache();

    /**
     * 刷新之后，其他业务处理，比如监听器的注册
     */
    protected void afterInitCache() {
    }

    /**
     * 刷新之后，其他业务处理，比如缓存变通通知
     */
    protected void afterRefreshCache() {
        //有需要后续动作的缓存实现
    }
}